<template>
    <header-footer :commonData="{$parent:$parent}">
        <div class="questionPage" v-cloak>
            <div class="crumb questionCrumb">
                <ul>
                    <li class="f_left">当前位置：</li>
                    <li class="f_left">
                        <router-link to="/home">首页></router-link>
                    </li>
                    <li class="f_left">在线学习</li>
                </ul>
            </div>
            <div class="relative questionCrumb">
                <div class="question_box f_left">
                    <div class="question_list">
                        <p class="question_anli" v-if="!String.isEmptyOrNUll(questionList.backgroundText)">
                            案例：{{questionList.backgroundText}}</p>
                        <img :src="'/static/img/question/'+questionList.typeName+'.png'" class="question_img_type">
                        <dl class="question_list_dl">
                            <dt>
                                {{questionList.sort}}、{{questionList.question}}
                            </dt>
                            <div class="text_center" style="margin-bottom: 20px;">
                                <img v-if="!String.isEmptyOrNUll(questionList.imgUrl)" :src="questionList.imgUrl">
                            </div>
                            <dd v-for="(option,index) in questionList.container" :key="index"
                                @click="optionClick(option.k)">
                                <img :src="'/static/img/question/'+option.image+'.png'">
                                {{option.v}}
                            </dd>
                        </dl>
                    </div>
                    <div class="question_btns text_center">
                        <button class="question_prev" @click="prev">{{prevText}}</button>
                        <button class="question_next" @click="next">{{nextText}}</button>
                    </div>
                    <div class="question_anylise" v-if="isAnalysise">
                        <h3 class="question_anylise_title text_center">试题解析</h3>
                        <p class="question_anylise_answer color666">正确答案</p>
                        <p class="question_anylise_answer">{{questionList.rightAnswer}}</p>
                        <p class="question_anylise_answer color666">试题详解</p>
                        <p class="question_anylise_answer">{{questionList.analysis}}</p>
                    </div>
                </div>
                <div v-show="questionResetBtn" class="question_reset_btn">
                    <a @click="questionResetBtns">重置试卷</a>
                </div>
                <div class="question_reset_btn clear_btn" v-show="isErrQuestion">
                    <a @click="clearErrQuest(questionList.id)">清除该错题</a>
                </div>
                <div class="question_sort" @click="dialogVisible=true">
                    <img src="/static/img/question/questionSort.png" class="questionSortBtn">
                    <p>习题列表</p>
                    <!-- <img src="/static/img/question/icon.png" width="92px" height="92px"> -->
                </div>
                <div style="cursor: pointer;top: 526px;position: absolute;right: -100px;text-align: center;">
                    <img v-if="!String.isEmptyOrNUll(showercode)" :src="showercode"
                        @click="$refs.smallCodeChild.showSmallCode()" title="点击放大微信扫码学习" width="100px" height="100px">
                    <p style="color: #0066CC;">点击放大扫码<br />小程序学习</p>
                </div>
                <div class="clear"></div>
            </div>
        </div>
        <el-dialog title="答题卡" :visible.sync="dialogVisible" width="800px">
            <div class="sortLiBox">
                <ul class="">
                    <li :class="{isRight:list.isRight,isError:list.isError}" v-for="(list,index) in itemPools"
                        :key="index" @click="toQuestion(index)">{{list.sort}}</li>
                </ul>
                <div class="clear"></div>
            </div>
            <div class="question_dialog_sort_mark">
                <ul>
                    <li class="question_dialog_sort_gray f_left">
                        <span></span>灰色未做
                    </li>
                    <li class="question_dialog_sort_green f_left">
                        <span></span>绿色正确
                    </li>
                    <li class="question_dialog_sort_red f_left">
                        <span></span>红色错误
                    </li>
                </ul>
            </div>
        </el-dialog>
        <div v-if="isShoe"></div>
        <!-- 显示成绩 -->
        <el-dialog title="提示" :visible.sync="examScoreDialog" width="30%" :before-close="examScoreSure">
            <span>{{examScore}}</span>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="examScoreSure">确 定</el-button>
            </span>
        </el-dialog>
        <smallCode ref="smallCodeChild"></smallCode>
    </header-footer>
</template>

<script>
    var _this;
    import headerFooter from '../../../components/cont_education/header_and_footer.vue'
    import {
        setLocalForage,
        getLocalForage,
        removeLocalForage
    } from '../../../assets/basejs/auth.js'
    import smallCode from '../../../components/smallCode.vue'
    export default {
        name: 'exam',
        data() {
            return {
                questionResetBtn: false, //重置试卷按钮
                isShoe: false,
                examScoreDialog: false, //得分
                examScore: "",
                dialogVisible: false, //题号弹框
                lastQuestionDialog: false, //剩余题数弹框
                itemPools: [],
                questionAnLiLists: [],
                questionList: {
                    container: [{
                        k: "",
                        v: "",
                        image: ""
                    }]
                }, //当前题
                prevText: '上一题',
                nextText: '下一题',
                questHeight: "500px",
                isAnalysise: false, //是否显示解析
                isRight: false, //定义答对题样式
                isError: false, //定义答错题样式
                saveId: '', //保存做题记录
                saveErrId: '', // 保存错题集id
                saveQrErrId: '', // 错题集做题记录
                rightSum: 0, //对题
                errorSum: 0, //错题
                questionJson: {},
                recordNo: '',
                questionId: '',
                isErrQuestion: false,
                tradeNo: this.$route.params.tradeNo,
                showercode: "",
                isAddRecord: true
            }
        },
        beforeCreate() {
            _this = this;
        },
        mounted: function() {
            this.isErrQuestion = this.$route.params.isErr == 1 ? false : true
            this.getQuestionJson(this.$route.params.questionId);
            this.questionId = this.$route.params.questionId;
            this.studyTaskUserId = this.$route.params.studyTaskUserId;

            this.saveId = 'MAQR' + this.questionId;
            this.saveErrId = 'MAERR' + this.questionId;
            this.saveQrErrId = 'MAERRQR' + this.questionId;
            this.common.postNotLoading(this.api.getQRCode, {}, function(res) {
                if (!String.isEmptyOrNUll(res.resultMap)) {
                    _this.showercode = res.resultMap;
                }
            });
        },
        methods: {
            // getQuestion: function(questionId) {
            //     this.common.post(this.api.lunchQuestion, {
            //         questionId: questionId
            //     }, function(res) {
            //         _this.getQuestionJson(res.resultMap.questionId); //获取试题json
            //         _this.rid = res.resultMap.record.id;
            //         _this.saveId = 'MAQR' + _this.rid
            //         _this.saveErrId = 'MAERR' + _this.rid
            //         _this.saveQrErrId = 'MAERRQR' + _this.rid
            //     });
            // },
            getQuestionJson: function(qid) {
                this.common.post(this.api.getQuestionJson, {
                    qid: qid
                }, function(data) {
                    _this.getTrueQuestionJson(data.resultMap)
                });
            },
            getTrueQuestionJson: function(questionToken) {
                this.common.post(this.api.getTrueQuestionJson, {
                    questionToken: questionToken
                }, function(data) {
                    _this.recordNo = data.resultMap.recordNo;
                    _this.getQuestions(data.resultMap.address);
                });
            },
            getQuestions: function(url) {
                const options = {
                    method: 'GET',
                    mode: "no-cors",
                    credentials: 'include',
                    headers: {
                        "Content-Type": "text/plain"
                    },
                };
                window.fetch(url).then(response => response.text()).then(async response => {
                    let errId = String.isEmptyOrNUll(await getLocalForage(this.saveErrId)) ? [] : JSON
                        .parse(await getLocalForage(this.saveErrId));
                    if (this.isErrQuestion && errId.length == 0) {
                        this.$message.warning("当前没有错题集！");
                        this.$router.go(-1);
                        return
                    }

                    _this.questionJson = JSON.parse(response);
                    _this.itemPools = this.isErrQuestion ? _this.errQuestions(JSON.parse(response)
                        .itemPools, errId) : JSON.parse(response).itemPools;
                    if (JSON.parse(response).questionBackgrounds) {
                        _this.questionAnLiLists = JSON.parse(response).questionBackgrounds;
                        // _this.showAnLiQuestion=true;
                    }
                    _this.getQuestionRecord(); //获取进度
                })


            },
            errQuestions(eq, errId) {
                let newQ = []
                var obj = {};
                eq.forEach(function(v, i) {
                    obj[v.id] = v;
                });
                errId.forEach((v, i) => {
                    if (obj.hasOwnProperty(v)) {
                        obj[v].sort = i + 1;
                        newQ.push(obj[v]);
                    }
                })
                console.log(newQ)
                return newQ
            },
            getQuestionRecord: async function() { //获取进度
                if (this.isErrQuestion) {
                    let record = String.isEmptyOrNUll(await getLocalForage(this.saveQrErrId)) ? {} : JSON.parse(
                        await getLocalForage(this.saveQrErrId));
                    this.renderBefore(record);
                } else {
                    let record = String.isEmptyOrNUll(await getLocalForage(this.saveId)) ? {} : JSON.parse(
                        await getLocalForage(this.saveId));
                    this.renderBefore(record);
                }
            },
            renderBefore: function(data) {
                for (var k in data) {
                    this.itemPools.forEach(function(item, index) {
                        if (item.id == k) {
                            item.result = data[k].answer == undefined ? "" : data[k].answer;
                            item.isFinish = data[k].answer.length > 0;
                            if (_this.answerequal(data[k].answer, item.rightAnswer)) {
                                item.isRight = true;
                                item.isError = false;
                                _this.rightSum += 1;
                            } else if (item.result == '') {
                                item.isRight = false;
                                item.isError = false;
                            } else {
                                item.isRight = false;
                                item.isError = true;
                                _this.errorSum += 1;
                            }
                        }
                    });
                }
                this.refresh(this.itemPools[0]);
            },
            refresh: function(model) {
                model.result = model.result == undefined ? "" : model.result;
                model.isFinish = model.result.length > 0;

                for (var i = 0; i < _this.questionAnLiLists.length; i++) {
                    if (_this.questionAnLiLists[i].id == model.backgroundId) {
                        model.backgroundText = _this.questionAnLiLists[i].backGroundText
                    }
                }
                this.render(model);
            },
            render: function(model) {
                this.anylise(model);
                model.container.forEach(function(v, i) {
                    var o = v;
                    for (var j in o) {
                        var optionKey = o[j];
                        o.image = optionKey;
                        if (!model.isFinish) o.image = _this.containValue(model.result, optionKey) ?
                            "right" :
                            optionKey;
                        else if (_this.containValue(model.result, optionKey) && _this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = "right";
                        } else if (_this.containValue(model.result, optionKey) && !_this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = "error";
                        } else if (!_this.containValue(model.result, optionKey) && _this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = optionKey + "R";
                        }
                    }
                });
                if (model.isFinish == 0 && model.result.length > 0) {
                    this.nextText = "确定";
                } else {
                    this.nextText = "下一题";
                }
                _this.questionList = model;
                this.isShoe = true;
                this.isShoe = false;
                // console.log(this.questionList);
            },
            optionClick: function(optionKey) {
                var model = this.questionList;
                if (model.isFinish) {
                    return;
                }
                this.resultChange(model, optionKey);
                this.render(model);
            },
            resultChange: function(model, optionKey) {
                if (model.result.indexOf(optionKey) >= 0) {
                    model.result = model.result.replace(optionKey, "");
                } else if (model.typeName == "多选题") {
                    model.result += optionKey;
                } else {
                    model.result = optionKey;
                }
            },
            anylise: function(model) {
                var isOver = true;
                model.result = model.result == undefined ? "" : model.result;
                if (model.isFinish && !_this.answerequal(model.rightAnswer, model.result)) {
                    _this.isAnalysise = true;
                } else {
                    _this.isAnalysise = false;
                }
                this.itemPools.forEach(function(v, i) {
                    if (!v.isFinish) {
                        isOver = false
                        return isOver;
                    }
                })
                if (isOver) {
                    this.questionResetBtn = true;
                    this.questionResetBtns();
                }
            },
            questionResetBtns: function() {
                this.addRecord();
                this.$confirm('是否重置试卷?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    if (this.isErrQuestion) {
                        await removeLocalForage(_this.saveQrErrId);
                        this.$router.go(0);
                    } else {
                        _this.questionSubmit();
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            },
            containValue: function(str1, str2) {
                if (str1 == undefined) return false;
                return str1.indexOf(str2) >= 0;
            },
            answerequal: function(answer1, answer2) {
                var bl = true;
                if (answer1 == undefined || answer2 == undefined) return false;
                if (answer1.length != answer2.length) return false;
                answer1 = answer1.toUpperCase();
                answer2 = answer2.toUpperCase();
                answer1.split("").forEach(function(v, i) {
                    if (!_this.containValue(answer2, v)) {
                        bl = false;
                        return false;
                    }
                });
                return bl;
            },
            next: async function() {
                var model = this.questionList;
                var index = parseInt(this.questionList.sort);
                if (model.sort == this.itemPools[this.itemPools.length - 1].sort && this.nextText == "下一题") {
                    this.$message.warning('当前为最后一题！');
                    return;
                }
                if (this.nextText == "确定") {
                    model.isFinish = 1;
                    _this.nextText = "下一题";
                    _this.anylise(model);
                    _this.compareRightError(model);
                    if (this.isAddRecord) {
                        _this.addRecord();
                        this.isAddRecord = false;
                    }
                    let my_isRight = 0
                    if (_this.answerequal(model.rightAnswer, model.result)) {
                        model.isRight = true;
                        model.isError = false;
                        my_isRight = 1;
                        this.rightSum += 1;
                        _this.refresh(_this.itemPools[index]);
                    } else {
                        model.isRight = false;
                        model.isError = true;
                        my_isRight = 0
                        this.errorSum += 1
                        _this.refresh(_this.itemPools[index - 1]);
                        if (!this.isErrQuestion) {
                            let errState = String.isEmptyOrNUll(await getLocalForage(this.saveErrId)) ? [] : JSON
                                .parse(await getLocalForage(this.saveErrId));
                            if (errState.indexOf(model.id) == -1) {
                                errState.push(model.id)
                                await setLocalForage(this.saveErrId, JSON.stringify(errState))
                            }
                        }
                    }

                    let data = {
                        isRight: my_isRight,
                        answer: model.result
                    }
                    if (this.isErrQuestion) {
                        let state = String.isEmptyOrNUll(await getLocalForage(this.saveQrErrId)) ? {} : JSON.parse(
                            await getLocalForage(this.saveQrErrId));
                        state[model.id] = data
                        await setLocalForage(this.saveQrErrId, JSON.stringify(state))
                    } else {
                        let state = String.isEmptyOrNUll(await getLocalForage(this.saveId)) ? {} : JSON.parse(
                            await getLocalForage(this.saveId));
                        state[model.id] = data
                        setLocalForage(this.saveId, JSON.stringify(state))
                    }

                    return;
                }
                this.refresh(this.itemPools[index]);
            },
            addRecord: function() {
                this.common.post(this.api.addRecord, {
                    recordNo: this.recordNo,
                    studyTaskUserId: this.studyTaskUserId
                }, function(res) {});
            },
            compareRightError: function(model) {
                model.container.forEach(function(v, i) {
                    var o = v;
                    for (var j in o) {
                        var optionKey = o[j];
                        o.image = optionKey;
                        if (!model.isFinish) o.image = _this.containValue(model.result, optionKey) ?
                            "right" :
                            optionKey;
                        else if (_this.containValue(model.result, optionKey) && _this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = "right";
                        } else if (_this.containValue(model.result, optionKey) && !_this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = "error";
                        } else if (!_this.containValue(model.result, optionKey) && _this.containValue(model
                                .rightAnswer,
                                optionKey)) {
                            o.image = optionKey + "R";
                        }
                    }
                });
            },
            questionSubmit: function() {
                var _this = this;
                this.common.post(this.api.submitRecord, {
                    itemCount: this.itemPools.length,
                    trueCount: this.rightSum,
                    undoneCount: 0,
                    recordNo: this.recordNo,
                    studyTaskUserId: this.studyTaskUserId
                }, async function(res) {
                    await removeLocalForage(_this.saveId)
                    _this.$message.warning("当前习题已完成,试卷已重置！");
                    _this.examScore = res.resultMap;
                    setTimeout(function() {
                        _this.examScoreDialog = true;
                    }, 2000);
                })
            },
            examScoreSure: function() {
                this.examScoreDialog = false;
                this.common.toPage("/home/play/task/0/0/0/0");
            },
            prev: function() {
                var index = this.questionList.sort - 2;
                if (index == -1) {
                    this.$message.warning('当前为第一题！');
                    return;
                }
                this.prevreduction()
                this.refresh(this.itemPools[index]);
            },
            prevreduction: function() {
                var model = this.questionList;
                if (model.hasOwnProperty("isFinish") && !model.isFinish && model.result != "") {
                    model.result = ""
                }
            },
            toQuestion: function(index) {
                this.sortTi = index;
                this.dialogVisible = false;
                this.refresh(this.itemPools[index])
            },
            clearErrQuest: function(id) {
                this.$confirm('是否清除该错题?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let errState = String.isEmptyOrNUll(await getLocalForage(this.saveErrId)) ? [] :
                        JSON.parse(await getLocalForage(this.saveErrId));
                    if (errState.length > 0) {
                        errState = errState.filter(v => v != id)
                        await setLocalForage(this.saveErrId, JSON.stringify(errState))
                        this.$router.go(0)
                    }
                }).catch(() => {});
            }
        },
        components: {
            headerFooter,
            smallCode
        }
    }
</script>

<style>
    .clear_btn {
        top: 190px;
    }

    .clear_btn a {
        font-size: 14px;
    }
</style>
